﻿using CM.UserCenter.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
 
using QL.Core.Log;
using CM.Resources.Web.Comm.Log;

namespace CM.Resources.Web.Filters
{
    public class WebExceptionHandle : HandleErrorAttribute
    {
        static private ILogger log = RYLogger.GetLogger("WebExceptionHandle");
        /// <summary>
        /// RY全局异常处理
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            try
            {
                log.Error(filterContext.Exception, "URL:{0};Form:{1}", filterContext.HttpContext.Request.Url.ToString(), filterContext.HttpContext.Request.Form.ToString());
                 
            }
            catch (Exception ex)
            {
                //X-Requested-With:XMLHttpRequest
            }
            var httpExc = filterContext.Exception as HttpException;
            if ((httpExc != null && httpExc.GetHttpCode() == 404))
            {
                //如果是404，不要跳转到500页面
                base.OnException(filterContext);
            }
            else
            {
                //ajax请求
                if ("XMLHttpRequest".Equals(filterContext.HttpContext.Request.Headers.Get("X-Requested-With")))
                {
                    filterContext.ExceptionHandled = true;
                    //filterContext.HttpContext.Response.Redirect("/home/error");
                    var result = new { ErrorCode = -1, ErrorMsg = "对不起!服务器发生了错误,请重试" };
                    filterContext.Result = new JsonResult() { ContentEncoding = Encoding.UTF8, ContentType = "text/json", Data = result };
                    return;
                }
                else if (!Configuration.Default.AppDebugModel)
                {
                    filterContext.ExceptionHandled = true;
                    //filterContext.HttpContext.Response.Redirect("/home/error");
                    filterContext.Result = new RedirectResult("/home/error");
                    return;
                }
                else
                    base.OnException(filterContext);
            }
        }

    }
}
